package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.EmployeeDao;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;

/**
 * @author Tang
 * @date 2023/4/11
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeDao, Employee> implements EmployeeService {
    /**
     * 新增员工
     *
     * @param employee
     */
    @Override
    public boolean addEmp(Employee employee, HttpSession session) {
        //优化一：
        /*LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        int count = this.count(wrapper);
        if (count > 0){
            return false;
        }*/

        //获取当前登录的用户id
        Long employeeId = (Long) session.getAttribute("employeeId");

        //1.补齐字段
        //密码必须加密处理，再存储到数据库中
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //优化：使用MP公共字段自动填充功能
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setCreateUser(employeeId);
//        employee.setUpdateUser(employeeId);

        //2.调用新增方法
        this.save(employee);
        return true;
    }

    /**
     * 分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Page<Employee> findPage(Integer page, Integer pageSize, String name) {
        //0. 添加分页拦截器
        //1. 创建分页查询对象Page(page,pageSize)
        Page<Employee> employeePage = new Page(page, pageSize);

        //2. 创建条件查询对象，设置name条件
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Employee::getName, name);

        //3. 调用分页方法selectPage()
        this.page(employeePage, wrapper);

        //4. 返回结果
        return employeePage;
    }
}
